import os
import smtplib
from email.mime.text import MIMEText
from email.header import Header


def newReport(report_dir):
    # 访问文件夹，通过下标找到文件并return
    list = os.listdir(report_dir)
    list1 = sorted(list)
    selected_file = os.path.join(report_dir, list1[0])
    print(selected_file)
    return selected_file


def SendReport(file_new):
    with open(file_new, "rb") as f:
        mail_body = f.read()
    f.close()

    mail_server = "smtp.163.com"  # 服务器：imap/smtp
    Port_number = 465  # SSL端口：465或587或25（无协议）
    mail_user = "wyh2085195880@163.com"  # 邮箱用户名
    mail_pwd = "KNEMUTGQFDHORHPE"  # 授权码
    sender = "wyh2085195880@163.com"  # 发送者邮箱账号名
    receivers = [sender, "2085195880@qq.com"]  # 接收者
    message = MIMEText(mail_body, "html", "utf-8")  # 文本信息
    message['From'] = Header(sender, "utf-8")  # 发件人名称
    message['To'] = Header("receiver", "utf-8")  # 收件人名称
    message['Subject'] = Header('提交信息', 'utf-8')  # 标题信息（类似gitee的提交信息）

    try:
        smtpObj = smtplib.SMTP_SSL(mail_server, Port_number)
        smtpObj.login(mail_user, mail_pwd)  # 登录
        smtpObj.sendmail(sender, sender, message.as_string())  # 发送人，接收人，文本信息
        print("邮件发送成功")
        smtpObj.quit()
    except smtplib.SMTPException as e:
        print("Error：无法发送邮件")
        print(e)


if __name__ == "__main__":
    report_dir = "E:\\download"
    file_new = newReport(report_dir)    # 给此方法传递目录，方法返回一个文件
    SendReport(file_new)    # 把文件传入此方法并运行
